<!-- eslint-disable @typescript-eslint/no-use-before-define -->
<script lang="ts" setup name="ManageTenant">
import type { Ref } from 'vue'
import { ref } from 'vue'
import { EType, tenantDict, tenantStatus } from './dict'
import { useFields } from './fields'
import { tenantApi } from '@/MainApp/apis/tenant'

const TenantModal = defineAsyncComponent(() => import('./TenantEditModal.vue'))
const NameAndIconModal = defineAsyncComponent(
  () => import('./TenantNameIconModal.vue')
)

const { t } = useConfig()
const { msgBoxWarnAsync, msgSuccess, msgError } = useMessage()
const { fieldList } = useFields()

// 新增、修改
const editData: Ref<typeof formKey | null> = ref(null)
const visible = ref(false)
const formKey = {
  // 租户名称
  name: '',
  // 租户类别,可用值:MASTER,NORMAL
  type: tenantDict[0].value,
  // 租户状态
  status: tenantStatus[0].value,
  // 租户域名
  domain: '',
  // 租户标识
  code: '',
  // 租户开始日期
  endDateTime: '',
  // 租户结束日期
  startDateTime: ''
  // // 租户Logo
  // logo: '',
  // // 租户icon
  // icon: '',
  // // 租户描述
  // remark: ''
}
const loading = ref(false)
const tadaTotal = ref(0)
const pageData = ref()
const tenantData = ref([])
const nameVisible = ref(false)

// 新增
const handAddTenant = () => {
  editData.value = null
  visible.value = true
}
// 修改
const handEditRow = (row: typeof formKey) => {
  editData.value = { ...row }
  visible.value = true
}
// 删除
const handDelete = (row: typeof formKey & { id: string; }) => {
  msgBoxWarnAsync(
    '确认删除',
    `删除后，租户【${row.name}】将无法继续使用技术中台提供的底层服务。确定删除吗？`,
    async () => {
      const { msg, success } = await tenantApi.deleteTenant(row.code)
      if (success) {
        queryTenant()
        msgSuccess(msg)
      }
      else {
        msgError(msg)
      }
    }
  )
}
const handResetPassword = (row: any) => {
  msgBoxWarnAsync(
    '管理员密码重置',
    `重置密码后，租户【${row.name}】管理员【${row.adminUsername}】的登录密码将被设置为默认密码，确定重置吗?`,
    async () => {
      const { msg, success } = await tenantApi.resetPasswordTenant(row.code)
      if (success) {
        queryTenant()
        msgSuccess(msg)
      }
      else {
        msgError(msg)
      }
    }
  )
}
const handRetryRow = (row: any) => {
  msgBoxWarnAsync('重试', `确认重新初始化租户[ ${row.name} ]吗?`, async () => {
    const { msg, success } = await tenantApi.retryTenant(row.id)
    if (success) {
      queryTenant()
      msgSuccess(msg)
    }
    else {
      msgError(msg)
    }
  })
}
// 查询
const queryTenant = async () => {
  loading.value = true
  const param = {
    ...pageData.value
  }
  const { success, data, total, msg } = await tenantApi.getTenantList(param)
  loading.value = false
  if (success) {
    tenantData.value = success ? data : []
    tadaTotal.value = total
  }
  else {
    msgError(msg)
  }
}
const handNameAndIconRow = (row: any) => {
  editData.value = { ...row }
  nameVisible.value = true
}

const closeTenantModal = () => {
  editData.value = null
  visible.value = false
}
const closeNameAndIcon = () => {
  editData.value = null
  nameVisible.value = false
}
</script>

<template>
  <IkPageMain fixed>
    <IkPageFull
      v-model="pageData"
      header-title="租户列表"
      :fields="fieldList"
      :table-data="tenantData"
      :total="tadaTotal"
      :loading="loading"
      :search="queryTenant"
    >
      <!-- 搜索slot -->
      <template #headerRight>
        <el-button
          v-role="'$ADD-TENANT'"
          type="primary"
          @click="handAddTenant"
        >
          {{ t("action.add") }}
        </el-button>
      </template>
      <template #type="{ data }">
        <el-tag
          :type="data.row.type === 'MASTER' ? '' : 'success'"
          effect="light"
        >
          <IkSvgIcon
            v-if="data.row.type === 'MASTER'"
            name="iksvg_yonghuguanli"
            type="primary"
            :padding="0"
          />
          {{ (EType as any)[data.row.type] }}
        </el-tag>
      </template>
      <template #status="{ data }">
        <el-tag
          :type="data.row.status === 'NORMAL' ? 'success' : ''"
          effect="light"
        >
          {{ data.row.statusName }}
        </el-tag>
        <el-button
          v-if="data.row.status === 'DATA_MIGRATE_FAIL'"
          v-role="'UPDATE-TENANT'"
          type="primary"
          text
          @click="handRetryRow(data.row)"
        >
          {{ t("action.retry") }}
        </el-button>
      </template>
      <template #operate="{ data }">
        <IkBtnContent :num="2">
          <IkSvgIcon
            v-role="'UPDATE-TENANT-LAYOUT'"
            name="icon-shezhi1"
            show-bg
            pop
            in-table
            :start-margin="false"
            :title="t('action.nameAndIcon')"
            @click="handNameAndIconRow(data.row)"
          />
          <IkSvgIcon
            v-role="'TENANT-ADMIN-RESET-PASSWORD'"
            name="icon-zhongzhi"
            show-bg
            pop
            in-table
            :title="t('action.adminPasswordReset')"
            @click="handResetPassword(data.row)"
          />
          <IkSvgIcon
            v-role="'UPDATE-TENANT'"
            name="icon-bianji"
            show-bg
            pop
            in-table
            :start-margin="false"
            :title="t('action.modify')"
            @click="handEditRow(data.row)"
          />
          <IkSvgIcon
            v-role="'DELETE-TENANT'"
            name="icon-shanchu"
            show-bg
            pop
            in-table
            :title="t('action.delete')"
            @click="handDelete(data.row)"
          />
        </IkBtnContent>
      </template>
    </IkPageFull>
    <TenantModal
      v-model:visible="visible"
      :form-key="formKey"
      :edit-data="editData!"
      :update:visible="closeTenantModal"
      @dataChange="queryTenant"
    />
    <NameAndIconModal
      v-model:visible="nameVisible"
      :edit-data="editData!"
      :update:visible="closeNameAndIcon"
      @dataChange="queryTenant"
    />
  </IkPageMain>
</template>
